/**
 * 
 */
package com.jolestar.yayaweibotong.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;

import com.google.appengine.api.users.UserServiceFactory;
import com.jolestar.yayaweibotong.YaYaConstants;
import com.jolestar.yayaweibotong.dao.UserDomain;
import com.jolestar.yayaweibotong.service.UserService;

/**
 * @author jolestar@gmail.com
 * 
 */
public class RegisterByGoogleAction extends AbstractAction {

	/**
	 * 
	 */
	public RegisterByGoogleAction() {
		super("register-by-google");
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.jolestar.yayaweibotong.controller.AbstractAction#doAction(javax.servlet
	 * .http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected String doAction(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.setAttribute("invite_enable", YaYaConstants.INVITE_ENABLE);
		com.google.appengine.api.users.UserService googleUserService = UserServiceFactory
				.getUserService();
		String thisURL = request.getRequestURI();
		String inviteToken = request.getParameter("invite_token");
		if (request.getUserPrincipal() != null) {
			String email = request.getUserPrincipal().getName();
			UserDomain user = UserService.ServiceHolder.getInstance().getUser(
					email);
			if (user != null) {
				return "redirect:/login?auth=google";
			} else {
				if (YaYaConstants.INVITE_ENABLE) {
					if (StringUtils.isBlank(inviteToken)) {
						return this.sendError(request, "需要邀请码.");
					}
					if (!UserService.ServiceHolder.getInstance()
							.validateInviteToken(inviteToken)) {
						return this.sendError(request, "邀请码无效.");
					}
				}
				user = UserService.ServiceHolder.getInstance().createUser(
						email, null, inviteToken);
				request.setAttribute("message", "注册成功。<br/>您的注册密码将会发送到邮箱:"
						+ email);
				request.setAttribute("user", user);
				request.setAttribute("backurl", "/login?auth=google");
				return "success";
			}
		} else {
			return "redirect:" + googleUserService.createLoginURL(thisURL);
		}
	}

	private String sendError(HttpServletRequest request, String message) {
		request.setAttribute("has_error", true);
		request.setAttribute("error", message);
		return "register_by_google";
	}

	@Override
	public String getPath() {
		return "/"+this.getName();
	}

}
